package org.example.monitor;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.google.gson.Gson;
import org.example.Row;
import org.example.VO;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

import static org.example.Main.process;

public class Inputer {
    public static void main(String[] args) throws IOException, ClassNotFoundException, URISyntaxException {
        final URL resource = Inputer.class.getClassLoader().getResource("run.log");
        final BufferedWriter writer = new BufferedWriter(new FileWriter(new File( resource.toURI())));
        final Properties prop = new Properties();
        final String filePath = Class.forName("org.example.Main").getClassLoader().getResource("prop.properties").getPath();
        prop.load(new FileInputStream(filePath));
        final String urlStr = prop.getProperty("get_url");
        final String username = prop.getProperty("Username");
        final String ticket = prop.getProperty("Access-ticket");
//        System.out.println(prop);
        System.out.println("urlStr = " + urlStr);
        System.out.println("username = " + username);
        System.out.println("ticket = " + ticket);
        final HttpRequest httpRequest = HttpRequest.get(urlStr);
        httpRequest.header("Accept", "application/json");
        httpRequest.header("Username", username);
        httpRequest.header("Access-ticket", ticket);
        final HttpResponse response = httpRequest.execute();
        final int status = response.getStatus();
        System.out.println("status = " + status);
        final String body = response.body();
        System.out.println(body);
        final Gson gson = new Gson();
        final VO vo = gson.fromJson(body, VO.class);

        final List<Row> rows = vo.getRows();
//        Executors.
        final List<String> programIdErrorList = new ArrayList<>();
        final List<Row> programIdWaitList = new ArrayList<>();
        final StringBuilder builder = new StringBuilder("select  count(*),sync_status  from data_sync_task where rogram_id in (");
        final StringBuilder builder2 = new StringBuilder("select  count(*) from data_sync_task where program_id in (");
        System.out.println("rows.size() = " + rows.size());
        final List<String> nulList = new ArrayList<>();
        int count = 0;
        int other = 0;
        int nul = 0;
        final List<Row> rowList = new ArrayList<>();
        for (int i = 0; i < rows.size(); i++) {
            final Row row = rows.get(i);
            final String syncStatus = row.getSyncStatus();

            if (syncStatus == null) {
                nulList.add(row.getItemId()+"");
                nul++;
                continue;
            }else {
                switch (syncStatus){
                    case "success":
                        count++;
                        continue;
                    case "wait_callback":
//                        programIdWaitList.add(row.getItemId() + "");
                        programIdWaitList.add(row);
                        continue;
                    case "error_xml":
                    case "error":
                        rowList.add(row);
                        programIdErrorList.add(row.getItemId()+"");
                        break;
                    default:
                        other++;
                }
            }
            if (null==syncStatus){

            }else {
                if (!"error_xml".equals(syncStatus) && !"error".equals(syncStatus)) {
                    continue;
                }
            }
            final Long itemId = row.getItemId();
            final Long appId = row.getAppId();
            final String recodeUrl = prop.getProperty("recode_url");
            final String reAdi_url = prop.getProperty("reAdi_url");
            final long start = System.currentTimeMillis();
//            System.out.println("row.getItemName() = " + row.getItemName());
//            process(itemId, appId, prop, recodeUrl, "转码");
//            final long transEnd = System.currentTimeMillis();
//            System.out.println("本次转码耗时"+(start-transEnd)+"ms");
//            process(itemId, appId, prop, reAdi_url, "注入");
//            final long adiEnd = System.currentTimeMillis();
//            System.out.println("本次注入耗时"+(adiEnd-transEnd)+"ms");

        }
        final String wait = programIdWaitList.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
        final String error = programIdErrorList.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
        builder.append(wait).append(") group by sync_status\\G;");
        builder2.append(error).append(")\\G;");
        System.out.println("查询等待状态的sql：");
//        System.out.println(builder);
        System.out.println("查询错误状态的sql：");
//        System.out.println(builder2);
        final int waitCount = programIdWaitList.size();
        final int errorCount = programIdErrorList.size();
        writer.write(new Date(System.currentTimeMillis()).toString());
        System.out.println("等待条数："+waitCount);
        writer.write("等待条数："+waitCount);
        System.out.println("错误条数："+errorCount);
        writer.write("错误条数："+errorCount);
        System.out.println("成功条数："+count);
        writer.write("成功条数："+count);
        System.out.println("其他状态条数："+other);
        writer.write("其他状态条数："+other);
        System.out.println("空状态："+nul);
        writer.write("空状态："+nul);
        System.out.println("total="+(waitCount+errorCount+count+other+nul));
        writer.write("total="+(waitCount+errorCount+count+other+nul));
        rowList.stream().forEach(row -> {
            System.out.println(row.getItemName()+"  -------- "+row.getCategoryPath());
        });
//        programIdWaitList.forEach(row -> {
//            System.out.println(new Date(row.getCreateTime())+"-----");
//        });
        final StringBuilder b = new StringBuilder("update data_sync_task set  where program_id in (");
        final String collect = programIdWaitList.stream().map(row -> "'" + row.getItemId() + "'").collect(Collectors.joining(","));
        b.append(collect).append(") where create_time<'2024-05-11 00:00:00';");
        System.out.println(b);

//        final String collect = rowList.stream().filter(row -> new Date(row.getCreateTime()).compareTo(new Date(2024, 05, 05)) > 0).map(row -> "'" + row.getItemId() + "'").collect(Collectors.joining(","));
//        System.out.println(collect);
//        rowList.stream().forEach(row -> System.out.println(new Date(row.getItemCreateTime())));

//        final String s = "14638731\t,14638691\t,14638651\t,14637971\t,14637891\t,14637851\t,14637771\t,14637931\t";
//        final Set<Long> collect = Arrays.stream(s.split(",")).map(String::trim).map(Long::new).collect(Collectors.toSet());
//        rowList.stream().filter(row -> collect.contains(row.getItemId())).forEach(row -> {
//            System.out.println(row.getItemName()+"  -------- "+row.getCategoryPath());
//        });
        writer.newLine();
        writer.flush();
        writer.close();
    }
}
